import { app, globalShortcut, BrowserWindow, ipcMain, dialog } from 'electron/main'

let shortcuts = []

const shortcutUpdate = (win, ipcMain) => {
    ipcMain.on("installshortcut", (event, text) => {
        try {
            if (shortcuts.length > 0) {
                shortcuts.forEach(item => {
                    globalShortcut.unregister(item.keyPressed);
                });
            }

            shortcuts = JSON.parse(text)

            shortcuts.forEach(item => {
                globalShortcut.register(item.keyPressed, function () {

                    if (win && !win.isDestroyed()) {
                        console.log(item.keyPressed);
                        win.webContents.send("use-shortcut", item);
                    }

                });
            });
        } catch (error) {
            console.error('Error occurred:');
        }


    })

    ipcMain.on("deleteshortcut", (event, text) => {
        try {
            if (shortcuts.length > 0) {
                globalShortcut.unregisterAll();
                shortcuts = []
            }
            
        } catch (error) {
            console.error('Error occurred:');
        }

    })
}

export default shortcutUpdate;